package com.dyz.leetcode._12_linkedList;

import com.dyz.leetcode.ListNode;

public class _203_removeElements {
    public ListNode removeElements(ListNode head, int val) {
        //1.删除节点
        while(head!=null && head.val==val){
            ListNode  delNode = head;
            head = head.next;
            delNode.next=null;
        }
        if(head==null){return null;}
        //2.删除非头节点
        ListNode curr = head.next;
        ListNode pre = head;
        while(curr!=null){
            if(curr.val==val){
                pre.next = curr.next;
                curr.next = null;
            }else{
                pre = curr;
            }
            curr = pre.next;
        }
        return head;
    }
    //哨兵节点
    public ListNode removeElements1(ListNode head, int val) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode curr = dummy.next;
        ListNode pre = dummy;
        while(curr!=null){
            if(curr.val==val){
                pre.next = curr.next;
                curr.next = null;
            }else{
                pre = curr;
            }
            curr = pre.next;
        }
        return dummy.next;

    }
}
